package com.wanhe.shoppingcart;

import com.google.gson.Gson;
import com.wanhe.base.net.ServerApi;
import com.wanhe.base.runner.Runner;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.websocket.WebSocketTool;
import com.wanhe.shoppingcart.bean.BatchOrder;
import com.wanhe.shoppingcart.bean.CartItem;
import com.wanhe.shoppingcart.bean.OrderDish;
import com.wanhe.shoppingcart.bean.OrderRequestModel;
import com.wanhe.shoppingcart.bean.SetMealCartItem;
import com.wanhe.shoppingcart.cuiyu.CuiYuOrderResult;
import com.wanhe.shoppingcart.cuiyu.CuiYuPot;
import com.wanhe.shoppingcart.cuiyu.CuiYuSetMeal;
import com.wanhe.shoppingcart.manager.CartManager;
import com.wanhe.shoppingcart.manager.ICartItem;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;


/**
 * Created by XieZaiWei on 2017/5/2.
 * 下单presenter
 */

public class OrderPresenter {
	private OnOrderListener mOnOrderListener;
	/**
	 * 下单请求返回值
	 */
	private int resultType = -1;
	private int c = 0;
	private int requestSize;
	/**
	 * 存放拼锅，单锅，套餐已下单列表，有顺序的，为了下单失败的时候显示ui用的
	 */
	private ArrayList<ICartItem> arrPotOrdered;
	/**
	 * 存放普通菜已下单列表，为了下单失败的时候显示ui用的
	 */
	private List<ICartItem> arrItem;

	private ServerApi api;
	private Runner runner;

	public OrderPresenter(){
		api = new ServerApi();
		runner = new Runner();
	}


	public void placeBatchOrder(String jobNumber, String tableNum, String count, String pwd) {
		//演示版本
		boolean isDom = SPUtils.getIsDemoSchema();
		if (isDom) {
			mOnOrderListener.onOrderSuccess();
			return;
		}

		arrPotOrdered = new ArrayList<>(3);
		List<ICartItem> items = CartManager.getInstance().getTotalCartItem();
		//先把鱼锅，套餐和其他菜分离开来
		arrItem = new ArrayList<>();//普通菜
		List<CuiYuPot> arrPotItem = new ArrayList<>();//拼锅和单锅
		List<CuiYuSetMeal> arrSetMealItem = new ArrayList<>();//套餐
		for (ICartItem item : items) {
			if (item instanceof CuiYuPot) {
				arrPotItem.add((CuiYuPot) item);

			} else if (item instanceof CuiYuSetMeal) {
				arrSetMealItem.add((CuiYuSetMeal) item);

			} else {
				arrItem.add(item);
			}
		}

		BatchOrder mBatchOrder = new BatchOrder();
		mBatchOrder.op = "BatchOrder";
		mBatchOrder.posTableId = tableNum;
		mBatchOrder.operId = jobNumber;
		mBatchOrder.password = pwd;
		mBatchOrder.nop = count;

		//如果只有一个锅的情况
		if (arrPotItem.size() == 1 && arrSetMealItem.size() == 0) {
			List<ICartItem> arrItem1 = new ArrayList<>();
			CuiYuPot chuiyuItem = arrPotItem.get(0);
			List<CartItem> arrGarnish = chuiyuItem.getArrChildItem();
			if (arrGarnish != null && arrGarnish.size() > 0) {
				//把辅料加入到订单列表中
				arrItem1.addAll(arrGarnish);
			}
			//把拼锅加入到订单列表中
			arrItem1.add(chuiyuItem);
			if (arrItem.size() > 0) {
				arrItem1.addAll(arrItem);
			}
			//把订单列表解析成订单对象，加入到下单列表中
			List<OrderDish> orderList = cuiYuParserToOrderList(arrItem1);
			mBatchOrder.addOrderList(orderList);
			//加入到拼锅等已下单列表中
			arrPotOrdered.add(chuiyuItem);

			batchOrder(mBatchOrder);
			return;
		}

		//如果只有一个套餐的情况
		if (arrPotItem.size() == 0 && arrSetMealItem.size() == 1) {
			List<ICartItem> arrSetMeal = new ArrayList<>();
			CuiYuSetMeal setMeal = arrSetMealItem.get(0);
			List<CartItem> setMealChilds = setMeal.getArrChildItem();
			//解析出套餐里鱼锅的辅料
			for (int j = 0; j < setMealChilds.size(); j++) {
				CartItem item = setMealChilds.get(j);
				if (item instanceof CuiYuPot) {
					CuiYuPot pot = (CuiYuPot) item;
					List<CartItem> arrGarnish = pot.getArrChildItem();
					if (arrGarnish != null && arrGarnish.size() > 0) {
						//把套餐里鱼锅的辅料加入下单列表中
						arrSetMeal.addAll(arrGarnish);
					}
				}
			}
			arrSetMeal.add(setMeal);
			if (arrItem.size() > 0) {
				arrSetMeal.addAll(arrItem);
			}
			List<OrderDish> orderList = cuiYuSetMealParserToOrderList(arrSetMeal);
			mBatchOrder.addOrderList(orderList);
			//加入到拼锅等已下单列表中
			arrPotOrdered.add(setMeal);
			batchOrder(mBatchOrder);
			return;
		}


		//把每个拼锅里的辅料解析出来，生成一个订单
		for (int i = 0; i < arrPotItem.size(); i++) {
			List<ICartItem> arrItem1 = new ArrayList<>();
			CuiYuPot chuiyuItem = arrPotItem.get(i);
			List<CartItem> arrGarnish = chuiyuItem.getArrChildItem();
			if (arrGarnish != null && arrGarnish.size() > 0) {
				//把辅料加入到订单列表中
				arrItem1.addAll(arrGarnish);
			}
			//把拼锅加入到订单列表中
			arrItem1.add(chuiyuItem);
			//把订单列表解析成订单对象，加入到下单列表中
			List<OrderDish> orderList = cuiYuParserToOrderList(arrItem1);
			mBatchOrder.addOrderList(orderList);
			//加入到拼锅等已下单列表中
			arrPotOrdered.add(chuiyuItem);
		}

		//把套餐解析成一个订单对象
		for (int i = 0; i < arrSetMealItem.size(); i++) {
			List<ICartItem> arrSetMeal = new ArrayList<>();
			CuiYuSetMeal setMeal = arrSetMealItem.get(i);
			List<CartItem> setMealChilds = setMeal.getArrChildItem();
			//解析出套餐里鱼锅的辅料
			for (int j = 0; j < setMealChilds.size(); j++) {
				CartItem item = setMealChilds.get(j);
				if (item instanceof CuiYuPot) {
					CuiYuPot pot = (CuiYuPot) item;
					List<CartItem> arrGarnish = pot.getArrChildItem();
					if (arrGarnish != null && arrGarnish.size() > 0) {
						//把套餐里鱼锅的辅料加入下单列表中
						arrSetMeal.addAll(arrGarnish);
					}
				}
			}
			arrSetMeal.add(setMeal);
			List<OrderDish> orderList = cuiYuSetMealParserToOrderList(arrSetMeal);
			mBatchOrder.addOrderList(orderList);
			//加入到拼锅等已下单列表中
			arrPotOrdered.add(setMeal);
		}

		//把其他菜品解析成一个订单对象
		if (arrItem != null && arrItem.size() > 0) {
			List<OrderDish> orderList = cuiYuParserToOrderList(arrItem);
			mBatchOrder.addOrderList(orderList);
		}

		batchOrder(mBatchOrder);

	}

	private List<OrderDish> cuiYuParserToOrderList(List<? extends ICartItem> items) {
		List<OrderDish> orderlist = null;
		if (ObjectUtil.checkObjectList(items)) {
			orderlist = new ArrayList<>();
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				if (fooditem.getSize() != null) {
					dish.DishSize = fooditem.getSize();
				}
				//如果有口味
				if (fooditem.getTags() != null && fooditem.getTags().size() > 0) {
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}

		return orderlist;
	}

	private List<OrderDish> cuiYuSetMealParserToOrderList(List<? extends ICartItem> items) {
		List<OrderDish> orderlist = new ArrayList<>();
		if (ObjectUtil.checkObjectList(items)) {
			orderlist = new ArrayList<>();
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				//判断是否为套餐
				if (item instanceof SetMealCartItem) {
					//填充订单数据 子菜品的数据填充
					SetMealCartItem setMealCartItem = (SetMealCartItem) item;
					List<CartItem> childItem = setMealCartItem.getArrChildItem();
					if (ObjectUtil.checkObjectList(childItem)) {
						List<OrderDish> dishs = new ArrayList<>();
						dish.Dishes = dishs;
						for (CartItem item1 : childItem) {
							OrderDish childDish = new OrderDish();
							childDish.DishesName = item1.getDish().getVch_dishname();
							childDish.Amount = String.valueOf(item1.getCount());
							childDish.DishesID = item1.getDish().getCh_dishno();
							childDish.DishSize = item1.getSize();
							childDish.DishTags = item1.getTags();
							childDish.SetItemKey = item1.getDish().getSetitem_key();
							childDish.Amount = String.valueOf(item1.getCount());
							dish.Dishes.add(childDish);
						}
					}
				} else {
					dish.DishSize = fooditem.getSize();
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}
		return orderlist;
	}

	private void batchOrder(BatchOrder batchOrder) {
		try {
			String postEntity = new String(new Gson().toJson(batchOrder).getBytes("UTF-8"), "UTF-8");
			JSONObject object = new JSONObject();
			object.put("paramJsonStr", postEntity.toString());
			mOnOrderListener.showLoading();

			runner.execute(api.batchOrder(postEntity), new Consumer<CuiYuOrderResult>() {

				@Override
				public void accept(@NonNull CuiYuOrderResult orderResult) throws Exception {

					//resultType等于0，表示有下单失败的情况
					if (orderResult.ResultType == 0) {
						//第一个flag的值如果为2，表示是账号密码之类的错误,否则表示菜品下单失败
						if (!ObjectUtil.checkObjectList(orderResult.ResultFlags)) {
							mOnOrderListener.onOrderFail("下单结果数据异常，请联系服务员");
							return;
						}
						int flag = orderResult.ResultFlags.get(0);
						if (flag == 2) {
							mOnOrderListener.onOrderFail(orderResult.ResultMsg);
						} else {
							ArrayList<ICartItem> arrOrderSuccess = new ArrayList<>(3);
							ArrayList<ICartItem> arrOrderFail = new ArrayList<>(3);

							//如果拼锅下单列表大于零且等于总下单列表，说明只有拼锅类型的菜品
							if (arrPotOrdered.size() > 0 && arrPotOrdered.size() == orderResult.ResultFlags.size()) {
								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
									flag = orderResult.ResultFlags.get(i);
									switch (flag) {
										case 0://下单失败
											arrOrderFail.add(arrPotOrdered.get(i));
											break;

										case 1://下单成功
											arrOrderSuccess.add(arrPotOrdered.get(i));
											break;

										default:
											break;
									}
								}

								//如果拼锅下单列表等于零说明只有普通类型的菜品
							} else if (arrPotOrdered.size() == 0) {
								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
									flag = orderResult.ResultFlags.get(i);
									switch (flag) {
										case 0://只有普通类型的时候，只有失败才显示ui，成功的话就直接跳转到登录界面了
											arrOrderFail.addAll(arrItem);
											break;
										default:
											break;
									}
								}

								//拼锅和普通两种类型菜品都有
							} else {
								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
									flag = orderResult.ResultFlags.get(i);
									//表示拼锅，单锅，套餐是否下单成功
									if (i != orderResult.ResultFlags.size() - 1) {
										switch (flag) {
											case 0://下单失败
												arrOrderFail.add(arrPotOrdered.get(i));
												break;

											case 1://下单成功
												arrOrderSuccess.add(arrPotOrdered.get(i));
												break;

											default:
												break;
										}

										//最后一个是表示普通菜品列表是否下单成功
									} else {
										switch (flag) {
											case 0://下单失败
												arrOrderFail.addAll(arrItem);
												break;

											case 1://下单成功
												arrOrderSuccess.addAll(arrItem);
												break;

											default:
												break;
										}
									}

								}
							}

							mOnOrderListener.onBatchOrderFail(arrOrderSuccess, arrOrderFail);
							// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
							SellOutPresenter presenter = new SellOutPresenter();
							presenter.getSellOutData();

						}

						//resultType等于1，表示所有下单都成功
					} else if (orderResult.ResultType == 1) {
						mOnOrderListener.onOrderSuccess();
						// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
						SellOutPresenter presenter = new SellOutPresenter();
						presenter.getSellOutData();

					}

				}
			});

//			AppServerFactory.getFactory().getOrderOperation().sendOrder(object.toString(), new BaseJsonResponseListener() {
//				@Override
//				public void onResponse(JSONObject response) {
//					mOnOrderListener.hideLoading();
//					String result = response.toString();
//					Logger.i(Logger.TAG, "==batchOrder==result==" + result);
//					CuiYuOrderResult orderResult = new Gson().fromJson(result, CuiYuOrderResult.class);
//					//resultType等于0，表示有下单失败的情况
//					if (orderResult.ResultType == 0) {
//						//第一个flag的值如果为2，表示是账号密码之类的错误,否则表示菜品下单失败
//						if (!ObjectUtil.checkObjectList(orderResult.ResultFlags)) {
//							mOnOrderListener.onOrderFail("下单结果数据异常，请联系服务员");
//							return;
//						}
//						int flag = orderResult.ResultFlags.get(0);
//						if (flag == 2) {
//							mOnOrderListener.onOrderFail(orderResult.ResultMsg);
//						} else {
//							ArrayList<CartManager.CartItem> arrOrderSuccess = new ArrayList<>(3);
//							ArrayList<CartManager.CartItem> arrOrderFail = new ArrayList<>(3);
//
//							//如果拼锅下单列表大于零且等于总下单列表，说明只有拼锅类型的菜品
//							if (arrPotOrdered.size() > 0 && arrPotOrdered.size() == orderResult.ResultFlags.size()) {
//								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
//									flag = orderResult.ResultFlags.get(i);
//									switch (flag) {
//										case 0://下单失败
//											arrOrderFail.add(arrPotOrdered.get(i));
//											break;
//
//										case 1://下单成功
//											arrOrderSuccess.add(arrPotOrdered.get(i));
//											break;
//
//										default:
//											break;
//									}
//								}
//
//								//如果拼锅下单列表等于零说明只有普通类型的菜品
//							} else if (arrPotOrdered.size() == 0) {
//								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
//									flag = orderResult.ResultFlags.get(i);
//									switch (flag) {
//										case 0://只有普通类型的时候，只有失败才显示ui，成功的话就直接跳转到登录界面了
//											arrOrderFail.addAll(arrItem);
//											break;
//										default:
//											break;
//									}
//								}
//
//								//拼锅和普通两种类型菜品都有
//							} else {
//								for (int i = 0; i < orderResult.ResultFlags.size(); i++) {
//									flag = orderResult.ResultFlags.get(i);
//									//表示拼锅，单锅，套餐是否下单成功
//									if (i != orderResult.ResultFlags.size() - 1) {
//										switch (flag) {
//											case 0://下单失败
//												arrOrderFail.add(arrPotOrdered.get(i));
//												break;
//
//											case 1://下单成功
//												arrOrderSuccess.add(arrPotOrdered.get(i));
//												break;
//
//											default:
//												break;
//										}
//
//										//最后一个是表示普通菜品列表是否下单成功
//									} else {
//										switch (flag) {
//											case 0://下单失败
//												arrOrderFail.addAll(arrItem);
//												break;
//
//											case 1://下单成功
//												arrOrderSuccess.addAll(arrItem);
//												break;
//
//											default:
//												break;
//										}
//									}
//
//								}
//							}
//
//							mOnOrderListener.onBatchOrderFail(arrOrderSuccess, arrOrderFail);
//							// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
//							SellOutPresenter presenter = new SellOutPresenter();
//							presenter.getSallOutData();
//
//						}
//
//						//resultType等于1，表示所有下单都成功
//					} else if (orderResult.ResultType == 1) {
//						mOnOrderListener.onOrderSuccess();
//						// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
//						SellOutPresenter presenter = new SellOutPresenter();
//						presenter.getSallOutData();
//
//					}
//				}
//			}, new BaseResponseErrorListener() {
//				@Override
//				public void onErrorResponse(VolleyError error) {
//					mOnOrderListener.hideLoading();
//					mOnOrderListener.onOrderFail("网络错误，下单失败");
//				}
//			});
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void ChuiYuOrder(String jobNumber, String tableNum, String count, String pwd) {
		List<ICartItem> items = CartManager.getInstance().getTotalCartItem();
		//先把鱼锅和其他菜分离开来
		List<ICartItem> arrItem = new ArrayList<>();//普通菜
		List<CuiYuPot> arrChuiYuItem = new ArrayList<>();//拼锅
		for (ICartItem item : items) {
			if (item instanceof CuiYuPot) {
				arrChuiYuItem.add((CuiYuPot) item);
			} else {
				arrItem.add(item);
			}
		}

		OrderRequestModel order = new OrderRequestModel();
		order.setOp("OrderDishNew");
		order.setOperID(jobNumber);//工号
		order.setTablename(tableNum);//桌号
		order.setMannum(count);//人数
		order.setPassword(pwd);//密码
		order.setPreorderbillid("123456");
		order.setFlowid(UUID.randomUUID().toString());

		//如果有普通菜
		if (arrItem.size() > 0) {
			order = parserToOrder1(arrItem, order);
		}

		if (arrChuiYuItem.size() > 0) {
			//把每个拼锅里的辅料解析出来
			for (int i = 0; i < arrChuiYuItem.size(); i++) {
				List<ICartItem> arrItem1 = new ArrayList<>();
				CuiYuPot chuiyuItem = arrChuiYuItem.get(i);
				//把拼锅加入到订单列表中
				arrItem1.add(chuiyuItem);
				//如有辅料，把辅料加入订单列表中
				List<CartItem> arrGarnish = chuiyuItem.getArrChildItem();
				if (arrGarnish != null && arrGarnish.size() > 0) {
					//把辅料加入到订单列表中
					arrItem1.addAll(arrGarnish);
					//把拼锅里的辅料清除
					//                    chuiyuItem.getArrChildItem().clear();
				}
				order = parserToOrder1(arrItem1, order);
			}

		}

		order(order);
	}

	public void placeOrder(String jobNumber, String tableNum, String count, String pwd) {
		//设置提交的数据
		List<ICartItem> items = CartManager.getInstance().getTotalCartItem();
		List<OrderDish> orderlist = new ArrayList<>();
		if (ObjectUtil.checkObjectList(items)) {
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				//判断是否为套餐
				if (item instanceof SetMealCartItem) {
					//填充订单数据 子菜品的数据填充
					SetMealCartItem setMealCartItem = (SetMealCartItem) item;
					List<CartItem> childItem = setMealCartItem.getArrChildItem();
					if (ObjectUtil.checkObjectList(childItem)) {
						List<OrderDish> dishs = new ArrayList<>();
						dish.Dishes = dishs;
						for (CartItem item1 : childItem) {
							OrderDish childDish = new OrderDish();
							childDish.DishesName = item1.getDish().getVch_dishname();
							childDish.Amount = String.valueOf(item1.getCount());
							childDish.DishesID = item1.getDish().getCh_dishno();
							childDish.DishSize = item1.getSize();
							childDish.DishTags = item1.getTags();
							childDish.SetItemKey = item1.getDish().getSetitem_key();
							childDish.Amount = String.valueOf(item1.getCount());
							dish.Dishes.add(childDish);
						}
					}
				} else {
					dish.DishSize = fooditem.getSize();
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}

		OrderRequestModel model3 = new OrderRequestModel();
		model3.setOp("OrderDishNew");
		model3.setOperID(jobNumber);//工号
		model3.setTablename(tableNum);//桌号
		model3.setMannum(count);//人数
		model3.setPassword(pwd);//密码
		model3.setPreorderbillid("123456");
		model3.setOrderdishes(orderlist);
		model3.setFlowid(UUID.randomUUID().toString());

		try {
			String postEntity = new String(new Gson().toJson(model3).getBytes("UTF-8"), "UTF-8");
			JSONObject object = new JSONObject();
			object.put("paramJsonStr", postEntity.toString());
			mOnOrderListener.showLoading();
//			AppServerFactory.getFactory().getOrderOperation().sendOrder(object.toString(), new BaseJsonResponseListener() {
//				@Override
//				public void onResponse(JSONObject response) {
//					mOnOrderListener.hideLoading();
//					String result = response.toString();
//					OldBaseModel model = new Gson().fromJson(result, OldBaseModel.class);
//					if (model.getResultType() == 1) {
//						mOnOrderListener.onOrderSuccess();
//						// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
//						SellOutPresenter presenter = new SellOutPresenter();
//						presenter.getSallOutData();
//
//					} else {
//						mOnOrderListener.onOrderFail(model.getResultMsg());
//					}
//				}
//			}, new BaseResponseErrorListener() {
//				@Override
//				public void onErrorResponse(VolleyError error) {
//					mOnOrderListener.hideLoading();
//					mOnOrderListener.onOrderFail("网络错误，下单失败");
//				}
//			});
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void MultiPlaceOrder(String jobNumber, String tableNum, String count, String pwd) {
		List<ICartItem> items = CartManager.getInstance().getTotalCartItem();
		//先把鱼锅，套餐和其他菜分离开来
		List<ICartItem> arrItem = new ArrayList<>();//普通菜
		List<CuiYuPot> arrPotItem = new ArrayList<>();//拼锅和单锅
		List<CuiYuSetMeal> arrSetMealItem = new ArrayList<>();//套餐
		for (ICartItem item : items) {
			if (item instanceof CuiYuPot) {
				arrPotItem.add((CuiYuPot) item);

			} else if (item instanceof CuiYuSetMeal) {
				arrSetMealItem.add((CuiYuSetMeal) item);

			} else {
				arrItem.add(item);
			}
		}

		ArrayList<OrderRequestModel> arrOrder = new ArrayList<>();//存放下单对象
		//把每个拼锅里的辅料解析出来，生成一个订单
		for (int i = 0; i < arrPotItem.size(); i++) {
			List<ICartItem> arrItem1 = new ArrayList<>();
			CuiYuPot chuiyuItem = arrPotItem.get(i);
			List<CartItem> arrGarnish = chuiyuItem.getArrChildItem();
			if (arrGarnish != null && arrGarnish.size() > 0) {
				//把辅料加入到订单列表中
				arrItem1.addAll(arrGarnish);
				//                //把拼锅里的辅料清除
				//                chuiyuItem.getArrChildItem().clear();
			}
			//把拼锅加入到订单列表中
			arrItem1.add(chuiyuItem);
			//把订单列表解析成订单对象，加入到下单列表中
			OrderRequestModel order = cuiYuParserToOrder(arrItem1, jobNumber, tableNum, count, pwd);
			arrOrder.add(order);
		}

		//把套餐解析成一个订单对象
		for (int i = 0; i < arrSetMealItem.size(); i++) {
			List<ICartItem> arrSetMeal = new ArrayList<>();
			CuiYuSetMeal setMeal = arrSetMealItem.get(i);
			List<CartItem> setMealChilds = setMeal.getArrChildItem();
			//解析出套餐里鱼锅的辅料
			for (int j = 0; j < setMealChilds.size(); j++) {
				CartItem item = setMealChilds.get(j);
				if (item instanceof CuiYuPot) {
					CuiYuPot pot = (CuiYuPot) item;
					List<CartItem> arrGarnish = pot.getArrChildItem();
					if (arrGarnish != null && arrGarnish.size() > 0) {
						//把套餐里鱼锅的辅料加入下单列表中
						arrSetMeal.addAll(arrGarnish);
					}
				}
			}
			arrSetMeal.add(setMeal);

			OrderRequestModel order = parserToOrder(arrSetMeal, jobNumber, tableNum, count, pwd);
			arrOrder.add(order);
		}

		//把其他菜品解析成一个订单对象
		if (arrItem != null && arrItem.size() > 0) {
			OrderRequestModel order = cuiYuParserToOrder(arrItem, jobNumber, tableNum, count, pwd);
			arrOrder.add(order);
		}

//		Logger.i(Logger.TAG, "===arrOrder===" + arrOrder.size());
		//        Observable.from(arrOrder)
		////                .subscribeOn(Schedulers.io())
		//                .subscribeOn(AndroidSchedulers.mainThread())
		//                .observeOn(AndroidSchedulers.mainThread())
		//                .subscribe(new Subscriber<OrderRequestModel>() {
		//                    @Override
		//                    public void onCompleted() {
		//                        Logger.i(Logger.TAG, "===3=resultType=="+resultType);
		//                        switch (resultType) {
		//                            case 1://下单成功
		//                                // 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
		//                                SellOutPresenter presenter = new SellOutPresenter();
		//                                presenter.getSallOutData();
		//                                mOnOrderListener.onOrderSuccess();
		//                                break;
		//
		//                            case -1://网络问题失败
		//                                mOnOrderListener.hideLoading();
		//                                mOnOrderListener.onOrderFail("网络错误，下单失败");
		//                                break;
		//
		//
		//                            default://各种下单失败
		//                                mOnOrderListener.onOrderFail(resultMsg);
		//                                break;
		//                        }
		//
		//                    }
		//
		//                    @Override
		//                    public void onError(Throwable e) {
		//                        e.printStackTrace();
		//                    }
		//
		//                    @Override
		//                    public void onNext(OrderRequestModel order) {
		//                        multiOrder(order);
		//                    }
		//                });
		c = 0;
		requestSize = arrOrder.size();
//		Observable.from(arrOrder)
//				.subscribeOn(AndroidSchedulers.mainThread())
//				.observeOn(AndroidSchedulers.mainThread())
//				.subscribe(new Action1<OrderRequestModel>() {
//					@Override
//					public void call(OrderRequestModel orderRequestModel) {
//						if (c == 1) {
//							orderRequestModel.setPassword("0000");
//						}
//						multiOrder1(orderRequestModel);
//					}
//				});


	}

	private OrderRequestModel parserToOrder1(List<? extends ICartItem> items, OrderRequestModel order) {
		List<OrderDish> orderlist = new ArrayList<>();
		if (ObjectUtil.checkObjectList(items)) {
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				//如果有口味
				if (fooditem.getTags() != null && fooditem.getTags().size() > 0) {
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}

//		order.addOrderList(orderlist);
		return order;

	}

	private OrderRequestModel parserToOrder(List<? extends ICartItem> items, String jobNumber, String tableNum, String count, String pwd) {
		List<OrderDish> orderlist = new ArrayList<>();
		if (ObjectUtil.checkObjectList(items)) {
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				//判断是否为套餐
				if (item instanceof SetMealCartItem) {
					//填充订单数据 子菜品的数据填充
					SetMealCartItem setMealCartItem = (SetMealCartItem) item;
					List<CartItem> childItem = setMealCartItem.getArrChildItem();
					if (ObjectUtil.checkObjectList(childItem)) {
						List<OrderDish> dishs = new ArrayList<>();
						dish.Dishes = dishs;
						for (CartItem item1 : childItem) {
							OrderDish childDish = new OrderDish();
							childDish.DishesName = item1.getDish().getVch_dishname();
							childDish.Amount = String.valueOf(item1.getCount());
							childDish.DishesID = item1.getDish().getCh_dishno();
							childDish.DishSize = item1.getSize();
							childDish.DishTags = item1.getTags();
							childDish.SetItemKey = item1.getDish().getSetitem_key();
							childDish.Amount = String.valueOf(item1.getCount());
							dish.Dishes.add(childDish);
						}
					}
				} else {
					dish.DishSize = fooditem.getSize();
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}

		OrderRequestModel order = new OrderRequestModel();
		order.setOp("OrderDishNew");
		order.setOperID(jobNumber);//工号
		order.setTablename(tableNum);//桌号
		order.setMannum(count);//人数
		order.setPassword(pwd);//密码
		order.setPreorderbillid("123456");
		order.setOrderdishes(orderlist);
		order.setFlowid(UUID.randomUUID().toString());
		return order;

	}

	private OrderRequestModel cuiYuParserToOrder(List<? extends ICartItem> items, String jobNumber, String tableNum, String count, String pwd) {
		List<OrderDish> orderlist = new ArrayList<>();
		if (ObjectUtil.checkObjectList(items)) {
			for (int i = 0; i < items.size(); i++) {
				OrderDish dish = new OrderDish();//下单模型
				ICartItem item = items.get(i);//已选菜品类型
				CartItem fooditem = (CartItem) item;
				dish.DishesName = fooditem.getDish().getVch_dishname();//某菜类下的菜名
				dish.DishesID = fooditem.getDish().getCh_dishno();
				dish.Amount = String.valueOf(item.getCount());
				if (fooditem.getSize() != null) {
					dish.DishSize = fooditem.getSize();
				}
				//如果有口味
				if (fooditem.getTags() != null && fooditem.getTags().size() > 0) {
					dish.DishTags = fooditem.getTags();
				}
				orderlist.add(dish);
			}
		}

		OrderRequestModel order = new OrderRequestModel();
		order.setOp("OrderDishNew");
		order.setOperID(jobNumber);//工号
		order.setTablename(tableNum);//桌号
		order.setMannum(count);//人数
		order.setPassword(pwd);//密码
		order.setPreorderbillid("123456");
		order.setOrderdishes(orderlist);
		order.setFlowid(UUID.randomUUID().toString());
		return order;
	}

	private void order(OrderRequestModel order) {
//		Logger.i(Logger.TAG, "===order===" + order.getOrderdishes());
		try {
			String postEntity = new String(new Gson().toJson(order).getBytes("UTF-8"), "UTF-8");
			JSONObject object = new JSONObject();
			object.put("paramJsonStr", postEntity.toString());
			mOnOrderListener.showLoading();
//			AppServerFactory.getFactory().getOrderOperation().sendOrder(object.toString(), new BaseJsonResponseListener() {
//				@Override
//				public void onResponse(JSONObject response) {
//					mOnOrderListener.hideLoading();
//					String result = response.toString();
//					Logger.i(Logger.TAG, "==order==result==" + result);
//					OldBaseModel model = new Gson().fromJson(result, OldBaseModel.class);
//					if (model.getResultType() == 1) {
//						mOnOrderListener.onOrderSuccess();
//						// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
//						SellOutPresenter presenter = new SellOutPresenter();
//						presenter.getSallOutData();
//
//					} else {
//						mOnOrderListener.onOrderFail(model.getResultMsg());
//					}
//				}
//			}, new BaseResponseErrorListener() {
//				@Override
//				public void onErrorResponse(VolleyError error) {
//					mOnOrderListener.hideLoading();
//					mOnOrderListener.onOrderFail("网络错误，下单失败");
//				}
//			});
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private void multiOrder1(OrderRequestModel order) {
		try {
			String postEntity = new String(new Gson().toJson(order).getBytes("UTF-8"), "UTF-8");
			JSONObject object = new JSONObject();
			object.put("paramJsonStr", postEntity.toString());
//			AppServerFactory.getFactory().getOrderOperation().sendOrder(object.toString(), new BaseJsonResponseListener() {
//				@Override
//				public void onResponse(JSONObject response) {
//					String result = response.toString();
//					Logger.i(Logger.TAG, "==order==result==" + result);
//					OldBaseModel model = new Gson().fromJson(result, OldBaseModel.class);
//					resultType = model.getResultType();
//					if (resultType == 1) {
//						c++;
//						Logger.i(Logger.TAG, "===c===" + c);
//						if (c == requestSize) {
//							// 下完单后要重新刷新一次估清数据，不能继续使用内存中缓冲的数据了
//							SellOutPresenter presenter = new SellOutPresenter();
//							presenter.getSallOutData();
//							mOnOrderListener.hideLoading();
//							mOnOrderListener.onOrderSuccess();
//							Logger.i(Logger.TAG, "===c==11=" + c);
//						}
//					} else {
//						mOnOrderListener.hideLoading();
//						mOnOrderListener.onOrderFail(model.getResultMsg());
//						return;
//					}
//				}
//			}, new BaseResponseErrorListener() {
//				@Override
//				public void onErrorResponse(VolleyError error) {
//					mOnOrderListener.hideLoading();
//					mOnOrderListener.onOrderFail("网络错误，下单失败");
//				}
//			});
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}

	private void multiOrder(OrderRequestModel order) {
		try {
			String postEntity = new String(new Gson().toJson(order).getBytes("UTF-8"), "UTF-8");
			JSONObject object = new JSONObject();
			object.put("paramJsonStr", postEntity.toString());
			mOnOrderListener.showLoading();
//			AppServerFactory.getFactory().getOrderOperation().sendOrder(object.toString(), new BaseJsonResponseListener() {
//				@Override
//				public void onResponse(JSONObject response) {
//					mOnOrderListener.hideLoading();
//					String result = response.toString();
//					Logger.i(Logger.TAG, "==order==result==" + result);
//					OldBaseModel model = new Gson().fromJson(result, OldBaseModel.class);
//					resultType = model.getResultType();
//					if (resultType != 1) {
//						//                        resultMsg = model.getResultMsg();
//					}
//				}
//			}, new BaseResponseErrorListener() {
//				@Override
//				public void onErrorResponse(VolleyError error) {
//					resultType = -1;
//				}
//			});
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}


	/**
	 * webSocke模式的下单
	 * @param peopleNum
	 * @param account
	 * @param pwd
	 */
	public void webSocketPlaceOrder(String peopleNum, String account, String pwd){
		WebSocketTool.getInstance().placeOrder(peopleNum, account, pwd);
	}



	public void setOnOrderListener(OnOrderListener onOrderListener) {
		mOnOrderListener = onOrderListener;
	}


	public interface OnOrderListener {
		void onOrderSuccess();

		void onOrderFail(String msg);

		void showLoading();

		void hideLoading();

		void onBatchOrderFail(ArrayList<ICartItem> arrOrderSuccess, ArrayList<ICartItem> arrOrderFail);
	}

}
